const acorn = require('acorn')
const MagicString = require('magic-string')
function ast(str) {
  const astTree = acorn.parse(str, {
    locations: true, // 索引位置
    ranges: true,
    sourceType: "module",
    ecmaVersion: 7,
  })
  const nodesKey = astTree.body.filter(node => node.type == "VariableDeclaration").reduce((pre, cur) => {
    let key = cur.declarations[0].id.name
    pre[key] = cur
    return pre
  }, {})
  const callsKey = astTree.body.filter(node => node.type == "ExpressionStatement").reduce((pre, cur) => {
    let key = cur.expression.callee.name
    pre[key] = cur
    return pre
  }, {})
  const m = new MagicString(str);

  return Object.keys(callsKey).map(call => {

    return `${m.snip(nodesKey[call].start, nodesKey[call].end).toString()}
${m.snip(callsKey[call].start, callsKey[call].end).toString()}
`
  }).join()
}

function treeshaking(str) {
  const result = ast(str)
  console.log({ result })
  return result

}

module.exports = treeshaking
